import cbApi from "@rc/apis/cb/index.mjs";

export default {
    name: "chapter-dialog",
	props: {
		// 项目名称
		projectName: {
			type: String,
			default: "项目"
		},
		// 可以选择的科目列表[{subjectId:科目标识,subjectName:科目名称}]
		subjectList: {
			type: Array,
			default: () => []
		},
		// 默认的已选章节列表[{subjectId:科目标识,subjectName:科目名称,chapterId:章节标识,chapterName:章节名称,title:父子级标题展示名称}]
		defaultData: {
			type: Array,
			default: () => []
		},
		//是否显示弹窗
		visibly: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			isShow: this.visibly, // 内部的是否显示弹窗
			selectedSubjectId: "", // 当前选中的科目id
			treeData: [], //章节树
			cacheData: [] // 当前缓存的已选章节列表(最终提交时的数据)
		};
	},
	computed: {
		// 当前选中的所有章节id集合
		checkedKeys() {
			return this.cacheData.map((i) => i.chapterId);
		}
	},
	watch: {
		// 内部和外部的变量双向绑定
		isShow(val) {
			this.$emit("update:visibly", val);
		},
		visibly(val) {
			this.isShow = val;
		},
		// 科目列表变化时默认选中第一个科目
		subjectList: {
			handler(val) {
				if (val.length) {
					this.selectedSubjectId = val[0].subjectId;
				}
			},
			immediate: true
		},
		// 选中的科目变化时更新章节树
		selectedSubjectId: {
			handler(val) {
				if (val) {
					cbApi.queryChapterTree({
						data: {
							subjectId: val,
							chapterLevel: 2 // 最多只要2级的数据
						},
						success: (res) => {
							// 没有节的章不允许选中
							this.treeData = res.map((i) => ({ ...i, disabled: !i.children || !i.children.length }));
						}
					});
				}
			},
			immediate: true
		}
	},
	methods: {
		// 点击确定
		onSubmit() {
			this.$emit("submit", this.cacheData);
			this.isShow = false;
		},
		//选中节点切换时，更新选中列表
		checkChange() {
			const nodes = this.$refs.tree.getCheckedNodes(true);
			const otherData = this.cacheData.filter((i) => i.subjectId !== this.selectedSubjectId); // 当前存在的不属于当前科目的章节
			const subject = this.subjectList.find((i) => i.subjectId === this.selectedSubjectId); // 当前选中的科目对象
			const nodeData = nodes.map((i1) => {
				const parentName = this.treeData.find((i2) => i2.chapterId === i1.chapterParentId).chapterTitle;
				const title = subject.subjectName + "-" + parentName + "-" + i1.chapterTitle;
				return {
					title,
					subjectName: subject.subjectName,
					subjectId: subject.subjectId,
					chapterId: i1.chapterId,
					chapterName: i1.chapterTitle,
					chapterIds: i1.chapterParentId + "," + i1.chapterId
				};
			});
			this.cacheData = [...otherData, ...nodeData];
		}
	},
	created() {
		this.cacheData = JSON.parse(JSON.stringify(this.defaultData));
	}
};
